﻿using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System;
using System.Threading;

public class UDPClient
{
    string _remoteIp;
    ushort _port;
    byte[] recvData;

    UdpClient udpClientRecv;    //udp接收
    UdpClient udpClientSend;    //udp发送
    Thread recvThread;
    private StickClass stickClass;



    public UDPClient(ushort port,string remoteIp, int bufferLength,StickClass.OnOneMsgReceiveFinished oneMsgRecieved)
    {
        this._port = port;
        this._remoteIp = remoteIp;

        stickClass = new StickClass(NetManager.headBufferLength, oneMsgRecieved);
        recvData = new byte[bufferLength];
        udpClientSend = new UdpClient();
        udpClientRecv = new UdpClient(port);

        recvThread = new Thread(UDPReceive);

    }

    public void OpenClient()
    {
        isRunning = true;
        recvThread.Start();
    }

    public void StopClient()
    {
        isRunning = false;
        recvThread.Abort();
    }

    private bool isRunning = true;
    public void UDPReceive()
    {
        while (isRunning)
        {
            if (udpClientRecv == null || udpClientRecv.Available <1)
            {
                Thread.Sleep(100);
                continue;
            }

            lock (this)
            {
                IPAddress ipaddress = IPAddress.Parse(this._remoteIp);
                IPEndPoint remote = new IPEndPoint(ipaddress, this._port);
                recvData = udpClientRecv.Receive(ref remote);
                if (recvData.Length > 0)
                {
                    //Debug.LogFormat("received length： {0} ",recvData.Length);
                    stickClass.ProcessRecvData(recvData, recvData.Length);
                }
            }

            Thread.Sleep(100);
        }
    }

    public int UDPSend(byte[] data,string remoteIp,int remotePort)
    {
        IPAddress remoteIP = IPAddress.Parse(remoteIp);
        IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点 
        return udpClientSend.Send(data, data.Length, remotePoint);//将数据发送到远程端点 
    }

    public void Dispose()
    {
        isRunning = false;
        if (udpClientRecv != null) udpClientRecv.Close();
        if (recvThread != null) recvThread.Abort();
        udpClientRecv = null;
        recvThread = null;
    }
}
